package com.atguigu.bigdata.chapter06;

import com.atguigu.bigdata.bean.UserBehavior;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashSet;

/**
 * @Author lzc
 * @Date 2022/9/3 13:59
 */
public class Flink02_Project_UV {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env.setRuntimeMode(RuntimeExecutionMode.BATCH);
        
        env
            .readTextFile("input/UserBehavior.csv")
            .map(new MapFunction<String, UserBehavior>() {
                @Override
                public UserBehavior map(String line) throws Exception {
                    String[] data = line.split(",");
                    return new UserBehavior(
                        Long.valueOf(data[0]),
                        Long.valueOf(data[1]),
                        Integer.valueOf(data[2]),
                        data[3],
                        Long.valueOf(data[4])
                    );
                }
            })
            .filter(ub -> "pv".equals(ub.getBehavior()))
            .keyBy(UserBehavior::getBehavior)
            .process(new KeyedProcessFunction<String, UserBehavior, String>() {
                HashSet<Long> uidSet = new HashSet<>();
                
                @Override
                public void processElement(UserBehavior value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 计算uv的本质: 其实就是计算有多少个不同的用户
                    
                    // 如果set中添加成功就是新用户, 否则就是旧用户
                    if (uidSet.add(value.getUserId())) { // 返回值是true表示新元素
                        out.collect("uv的值: " + uidSet.size());
                    }
                    
                    
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
